﻿//------------------------------------------------------------------------------
// <copyright file="App.xaml.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.Threading;
using Microsoft.Internal.GamesTest.Rpc.Server;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Rpc.CSharpSample
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    public sealed partial class App : Application
    {
        /// <summary>
        /// Keeps reference to main page content to display messages
        /// </summary>
        private MainPage content;

        /// <summary>
        /// Timer used to run RPC server.
        /// </summary>
        private ThreadPoolTimer processRequestsTimer;

        /// <summary>
        /// Timer interval for the timer used to run RPC server.
        /// </summary>
        private TimeSpan processPendingRequestsInverval = TimeSpan.FromSeconds(0.1);

        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class.
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += this.OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            // Get the content page
            content = rootFrame.Content as MainPage;

            // Ensure the current window is active
            Window.Current.Activate();

            // Initialize and run the RPC servers
            this.Initialize(args);
            this.Run();
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            // Stop the event processing and close connections
            this.Stop();
            Hooks.Shutdown();

            deferral.Complete();
        }

        /// <summary>
        /// Initializes the RPC servers and prepares for running.
        /// </summary>
        /// <param name="arguments">Application launch arguments.</param>
        private void Initialize(LaunchActivatedEventArgs args)
        {
            try
            {
                // Get port from command line arguments
                int port = string.IsNullOrEmpty(args.Arguments) ? RpcServer.DefaultPort : int.Parse(args.Arguments);

                // Print the port initialized with
                content.DisplayMessage = string.Format(CultureInfo.CurrentCulture, "Initialized with port {0}", port);

                // Initialize the RPC server
                Hooks.Initialize(port);
            }
            catch (Exception error)
            {
                // Print errors from initializing the server
                if (content != null)
                {
                    content.DisplayMessage += string.Format(CultureInfo.CurrentCulture, "\n\n{0}", error.ToString());
                }
            }
        }

        /// <summary>
        /// Creates a periodic timer to process RPC server events.
        /// </summary>
        private void Run()
        {
            this.processRequestsTimer = ThreadPoolTimer.CreatePeriodicTimer(
                (source) =>
                {
                    Hooks.ProcessPendingRequests();
                },
                processPendingRequestsInverval);
        }

        /// <summary>
        /// Stops the timer that processes RPC server events.
        /// </summary>
        private void Stop()
        {
            if (this.processRequestsTimer != null)
            {
                this.processRequestsTimer.Cancel();
                this.processRequestsTimer = null;
            }
        }
    }
}
